<template>
  <el-scrollbar class="form-designer-container" :id="id">
    <LeftPanel :editingFieldDefinition="editingFieldDefinition" ref="LeftPanel"
               @removeField="removeField" @removeSubForm="removeSubForm"
               :form-definition="formDefinition" @selectField="selectField"/>
    <div data-role="container" className="form-designer-body" :style='formBodyStyle'>
    </div>
    <RightPanel :editingFieldDefinition="editingFieldDefinition" :designView="designView"
                :form-definition="formDefinition"/>
    <FormDesignFootPanel ref="FormDesignFootPanel" @select='selectView'
                         :views='formDefinition.views' :viewActionHelper="viewActionHelper"/>
  </el-scrollbar>
</template>

<script>
import LeftPanel from '@/components/form/FromDesigner/LeftPanel.vue';
import {guid, isEmpty, isNotEmpty} from '@/utils/CommonUtils';
import {DefaultFormDefinition, DefaultViewDefinition} from '@/components/form/DefaultFormDefinition';
import RightPanel from '@/components/form/FromDesigner/RightPanel.vue';
import {getAction} from '@/request/BaseRequest';
import FormDesignFootPanel from '@/components/form/FromDesigner/FormDesignFootPanel.vue';
import DraggerDesigner from '@/components/form/DraggerDesigner';
import ViewActonHelper from '@/components/form/FromDesigner/ViewActonHelper';

export default {
  name: 'FromDesigner',
  components: {
    FormDesignFootPanel,
    LeftPanel,
    RightPanel
  },
  data() {
    return {
      id: guid(),
      fieldCount: 0,
      fieldCounts: [{id: 'asdfalkaweogwef', count: 0}],
      designer: undefined,
      editingFieldDefinition: undefined,
      formDefinition: JSON.parse(JSON.stringify(DefaultFormDefinition)),
      designView: JSON.parse(JSON.stringify(DefaultViewDefinition)),
      viewActionHelper: null
    };
  },
  mounted() {
    let that = this;
    this.designer = new DraggerDesigner(this.id, {
      selectedComponent(ele) {
        that.selectedComponent(ele);
      },
      clearSelectedComponent() {
        that.clearSelectedComponent();
      },
      fieldCreated(ele, formName, subFormId) {
        that.fieldCreated(ele, formName, subFormId);
      },
      onViewChange() {
        that.viewChange();
      },
      getSubFormDefinition(subFormId) {
        return that.getSubFormDefinition(subFormId);
      },
      getFormDefinition() {
        return that.formDefinition;
      },
    });
    this.showMainView();
  },
  methods: {
    setData({formId}) {
      if (isNotEmpty(formId)) {
        this.loadFormDefinition(formId, () => {
          this.loadViews(formId);
          this.loadFields(formId);
          this.loadFlows(formId);
          this.loadMenus(formId);
          this.loadFieldCount(formId);
          this.loadSubForms(formId);
        });
      } else {
        this.formDefinition = JSON.parse(JSON.stringify(DefaultFormDefinition));
        this.viewActionHelper = new ViewActonHelper(this.formDefinition);
        this.$nextTick(() => {
          this.showMainView();
          // this.$refs.FieldList.refreshFieldTree();
        });
      }
    },
    loadFields(formId) {
      this.loading = true;
      getAction('/plat/platFormField/query', {formId, _orderBy: 'sort', _order: 'asc'}).then(data => {
        if (data.success) {
          this.formDefinition.fields = data.result;
          // this.$refs.FieldList.refreshFieldTree();
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      });
    },
    loadFormDefinition(formId, callback) {
      this.loading = true;
      getAction('/plat/platForm/queryById', {id: formId}).then(data => {
        if (data.success) {
          this.resolveDefaultFormDefinitionValues(data.result);
          this.formDefinition = data.result;
          this.viewActionHelper = new ViewActonHelper(this.formDefinition);
          callback();
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      });
    },
    loadFlows(formId) {
      this.loading = true;
      getAction('/plat/loadFlowModelByFormId', {formId}).then(data => {
        if (data.success) {
          this.formDefinition.flows = this.resolveDefaultFlowValues(data.result);
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      });
    },
    loadMenus(formId) {
      this.loading = true;
      getAction('/plat/platFormMenu/query', {formId}).then(data => {
        if (data.success) {
          this.formDefinition.menus = data.result;
        } else {
          this.$notification.error({message: data.message, duration: 3});
        }
        this.loading = false;
      });
    },
    loadFieldCount(formId) {
      this.loading = true;
      getAction('/plat/loadFieldCount', {formId}).then(data => {
        this.loading = false;
        if (data.success) {
          this.fieldCounts = data.result;
        }
      });
    },
    loadSubForms(formId) {
      this.loading = true;
      getAction('/plat/loadSubForms', {formId}).then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          this.setSubForms(result);
        }
      });
    },
    setSubForms(subForms) {
      this.formDefinition.subForms = subForms;
    },
    resolveDefaultFlowValues(flows) {
      if (!flows || flows.length <= 0) return;
      for (let i = 0; i < flows.length; i++) {
        let flow = flows[i];
        flow.flowDefinition = JSON.parse(flow.flowDefinition);
        flow.key = flow.id;
      }
      return flows;
    },
    loadViews(formId) {
      this.loading = true;
      getAction('/plat/platFormView/query', {
        formId,
        _order: 'asc',
        _orderBy: 'sort'
      }).then(data => {
        if (data.success) {
          this.formDefinition.views = data.result;
          this.showMainView();
        } else {
          this.$notification.error({message: data.message, result: data.result, duration: 3});
        }
        this.loading = false;
      });
    },
    getSubFormDefinition(subFormId) {
      let index = this.formDefinition.subForms.findIndex(s => s.id === subFormId);
      if (index !== -1) {
        return this.formDefinition.subForms[index];
      }
      return null;
    },
    viewChange() {
      this.resolveViewDesignDefinition();
    },
    resolveViewDesignDefinition() {
      console.log('resolveViewDesignDefinition!');
      this.designView.viewDesignDefinition = this.designer.getContentData();
    },
    showMainView() {
      this.$nextTick(() => {
        this.$refs.FormDesignFootPanel.selectMainView();
        this.viewActionHelper?.refreshViews();
      });
    },
    resolveDefaultFormDefinitionValues(formDefinition) {
      if (!formDefinition.values) formDefinition.values = [];
      if (!formDefinition.fields) formDefinition.fields = [];
      if (isEmpty(formDefinition.subForms)) formDefinition.subForms = [];

      if (!formDefinition.formName || formDefinition.formName === '') formDefinition.formName = undefined;
      if (!formDefinition.showName || formDefinition.showName === '') formDefinition.showName = undefined;
    },
    fieldCreated(fieldConfig, formName, subFormId) {
      if (!fieldConfig) {
        // 可能拖拽出来的是布局组件
      } else if (formName === 'subForm') {
        //拖拽出了明细表
        let index = this.formDefinition.subForms.findIndex(s => s.id === fieldConfig.id);
        if (index === -1) {
          this.formDefinition.subForms.push(fieldConfig);
          this.resolveSubFormShowName(fieldConfig);
          this.resolveSubFormName(fieldConfig);
        }
      } else if (formName === 'subFormItem') {
        //拖拽出了明细表字段
        let index = this.formDefinition.subForms.findIndex(s => s.id === subFormId);
        if (index !== -1) {
          let subForm = this.formDefinition.subForms[index];
          this.formDefinition.subForms[index].fields.push(fieldConfig);
          this.resolveSubFieldTableName(fieldConfig, subForm);
        }
      } else {
        //拖拽出了主表字段
        fieldConfig.formName = formName;
        this.resolveMainTableFieldName(fieldConfig);
        this.formDefinition.fields.push(fieldConfig);
      }
      this.$nextTick(() => {
        this.designer.bind();
        this.viewActionHelper.refreshViews();
      });
    },
    resolveSubFieldTableName(fieldConfig, subForm) {
      this.resolveTableFieldNameByFormId(fieldConfig, subForm.id);
    },
    resolveSubFormName(fieldConfig) {
      this.loading = true;
      getAction('/plat/loadFormsonName').then(data => {
        this.loading = false;
        if (data.success) {
          let result = data.result;
          fieldConfig.formName = result;
        }
      });
    },
    resolveSubFormShowName(fieldConfig) {
      let subForms = this.formDefinition.subForms;
      let count = 0;
      for (let i = 0; i < subForms.length; i++) {
        let subForm = subForms[i];
        let formName = subForm.showName;
        try {
          formName = formName.replace(/明细表/g, '');
          count = Math.max(parseInt(formName), count);
        } catch (e) {
        }
      }
      count++;
      fieldConfig.showName = `明细表${count}`;
    },
    selectedComponent(ele) {
      this.selectionElement = ele;
      this.showTab = 'formItem';
      this.$nextTick(() => {
        let fieldId = $(ele).attr('id');
        this.editingFieldDefinition = this.findFieldDefinitionById(fieldId);
      });
    },
    searchSubField(fieldId) {
      let subForms = this.formDefinition.subForms;
      for (let i = 0; i < subForms.length; i++) {
        let fields = subForms[i].fields;
        if (isEmpty(fields)) fields = [];
        for (let j = 0; j < fields.length; j++) {
          if (fields[j].id === fieldId) {
            return fields[j];
          }
        }
      }
      return field;
    },
    selectField(fieldId) {
      let field = this.findFieldDefinitionById(fieldId);
      if (isNotEmpty(field)) {
        this.editingFieldDefinition = field;
        this.designer.setSelectingComponentId(fieldId);
      }
    },
    findFieldDefinitionById(fieldId) {
      let mainFields = this.formDefinition.fields;
      let index = mainFields.findIndex(f => f.id === fieldId);
      if (index !== -1) {
        return mainFields[index];
      }

      //下面是查询明细表字段的逻辑
      return this.searchSubField(fieldId);
    },
    resolveMainTableFieldName(fieldConfig) {
      let formId = this.formDefinition.id;
      if (!formId) formId = 'main-id';
      this.resolveTableFieldNameByFormId(fieldConfig, formId);
    },
    resolveTableFieldNameByFormId(fieldConfig, formId) {
      let index = this.fieldCounts.findIndex(f => f.formId === formId);
      let fieldCount = null;
      if (index === -1) {
        fieldCount = {formId, count: 0};
        this.fieldCounts.push(fieldCount);
      } else {
        fieldCount = this.fieldCounts[index];
      }

      let tableFieldName = ++fieldCount.count + '';
      while (tableFieldName.length < 5) {
        tableFieldName = '0' + tableFieldName;
      }
      fieldConfig.tableFieldName = 'field_' + tableFieldName;
    },
    getData() {
      return this.formDefinition;
    },
    clearSelectedComponent() {
      this.selectionElement = null;
      this.showTab = 'form';
      this.editingFieldDefinition = undefined;
    },
    selectView(view) {
      this.designView = view;
      this.$nextTick(() => {
        this.designer.setViewData(this.designView);
      });
    },
    removeSubForm(subformId) {
      let list = this.formDefinition.subForms;
      let index = list.findIndex(s => s.id === subformId);
      if (index !== -1) {
        list.splice(index, 1);
        this.removeViewField(subformId);
      }
    },
    removeField(fieldId) {
      let mainFields = this.formDefinition.fields;
      let index = mainFields.findIndex(f => f.id === fieldId);
      //删除主表字段逻辑
      if (index !== -1) {
        mainFields.splice(index, 1);
      }

      this.removeViewField(fieldId);
    },
    removeViewField(fieldId) {
      let views = this.formDefinition.views;
      if (isEmpty(views)) views = [];
      for (let i = 0; i < views.length; i++) {
        let view = views[i];
        this.doRemoveViewField(view, fieldId);
      }
    },
    doRemoveViewField(view, fieldId) {
      if (view === this.designView) {
        $(`#${fieldId}`).remove();
      } else {
        let div = $(`<div></div>`)[0];
        div.innerHTML = view.viewDesignDefinition;
        $(div).find(`#${fieldId}`).remove();
        view.viewDesignDefinition = div.innerHTML;
      }

      this.viewChange();
      if (this.editingFieldDefinition && this.editingFieldDefinition.id === fieldId) {
        this.clearSelectedComponent();
      }
    },
  },
  computed: {
    formBodyStyle() {
      return {
        width: this.designView.width + 'px',
      };
    },
  }
};
</script>
